//
//  BRFAQListViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/10/8.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRFAQListViewController.h"
//#import "BRFAQListTableViewCell.h"
#import "BRFAQDetailViewController.h"
#import "BROderReportViewController.h"
#import "BRSupportView.h"
#import "BRFAQModel.h"
#import "YGCategoryView.h"
#import "BRFAQListCell.h"

@interface BRFAQListViewController ()<QMUITableViewDelegate,QMUITableViewDataSource>

@property (nonatomic,strong) BRSupportView *supportView;

@property (nonatomic,strong) NSDictionary *dataDic;

@property (nonatomic,strong) YGCategoryCustomView *faqCategoryView;

@property (nonatomic,assign) NSInteger selIndex;

@end

@implementation BRFAQListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.dataDic = @{};
    [self  setUI];
    
    [self requestFAQ];
    
    
    [self br_blockAction];
}

//- (NSArray *)datas {
//    return @[@"BRFAQSubTableViewCell *cell = [tableView",@"BRFAQSubTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@\"BRFAQSubTableViewCell\"]cell.contentView.backgroundColor = UIColor.qd_backgroundColorLighten;",@"BRFAQSubTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@\"BRFAQSubTableViewCell\"]cell.contentView."];
//}

#pragma mark - request --
- (void)requestFAQ {
    // 使用写死的配置数据，不再从接口获取
    NSArray *faqList = [self getHardcodedFAQData];
    self.dataDic = [self resetData:faqList];
        [self.tableView reloadData];
        [self showBREmptyView];
}

/// 获取写死的FAQ配置数据
- (NSArray<BRFAQModel *> *)getHardcodedFAQData {
    NSMutableArray *faqArray = [NSMutableArray array];
    
    // 订单问题 (type=3) - 对应第一个标签"订单问题"
    BRFAQModel *orderChargingModel = [[BRFAQModel alloc] init];
    orderChargingModel.faqId = 3001;
    orderChargingModel.type = 3;  // 订单问题
    orderChargingModel.title = Localized(@"faq_orderChargingTitle");
    orderChargingModel.content = Localized(@"faq_orderChargingContent");
    [faqArray addObject:orderChargingModel];
    
    // 充电宝归还后订单仍在计费
    BRFAQModel *orderStillChargingModel = [[BRFAQModel alloc] init];
    orderStillChargingModel.faqId = 3002;
    orderStillChargingModel.type = 3;  // 订单问题
    orderStillChargingModel.title = Localized(@"faq_orderStillChargingTitle");
    orderStillChargingModel.content = Localized(@"faq_orderStillChargingContent");
    [faqArray addObject:orderStillChargingModel];
    
    // 设备问题 (type=4) - 对应第二个标签"设备问题"
    BRFAQModel *notEjectedModel = [[BRFAQModel alloc] init];
    notEjectedModel.faqId = 4001;
    notEjectedModel.type = 4;  // 设备问题
    notEjectedModel.title = Localized(@"faq_notEjectedTitle");
    notEjectedModel.content = Localized(@"faq_notEjectedContent");
    [faqArray addObject:notEjectedModel];
    
    BRFAQModel *cannotChargeModel = [[BRFAQModel alloc] init];
    cannotChargeModel.faqId = 4002;
    cannotChargeModel.type = 4;  // 设备问题
    cannotChargeModel.title = Localized(@"faq_cannotChargeTitle");
    cannotChargeModel.content = Localized(@"faq_cannotChargeContent");
    [faqArray addObject:cannotChargeModel];
    
    BRFAQModel *howToReturnModel = [[BRFAQModel alloc] init];
    howToReturnModel.faqId = 4003;
    howToReturnModel.type = 4;  // 设备问题
    howToReturnModel.title = Localized(@"faq_howToReturnTitle");
    howToReturnModel.content = Localized(@"faq_howToReturnContent");
    [faqArray addObject:howToReturnModel];
    
    // 其他问题 (type=9) - 对应第三个标签"其他"
    BRFAQModel *contactPhoneModel = [[BRFAQModel alloc] init];
    contactPhoneModel.faqId = 9001;
    contactPhoneModel.type = 9;  // 其他问题
    contactPhoneModel.title = Localized(@"faq_contactPhoneTitle");
    contactPhoneModel.content = Localized(@"faq_contactPhoneContent");
    [faqArray addObject:contactPhoneModel];
    
    BRFAQModel *emailModel = [[BRFAQModel alloc] init];
    emailModel.faqId = 9002;
    emailModel.type = 9;  // 其他问题
    emailModel.title = Localized(@"faq_emailTitle");
    emailModel.content = Localized(@"faq_emailContent");
    [faqArray addObject:emailModel];
    
    BRFAQModel *addressModel = [[BRFAQModel alloc] init];
    addressModel.faqId = 9003;
    addressModel.type = 9;  // 其他问题
    addressModel.title = Localized(@"faq_addressTitle");
    addressModel.content = Localized(@"faq_addressContent");
    [faqArray addObject:addressModel];
    
    return faqArray;
}

- (NSDictionary *)resetData:(NSArray <BRFAQModel *>*)faqList {
    
    // 问题类型: 1-租借问题 2-归还问题 3-订单问题 4-充电宝问题 5-收费问题 6-钱包问题 7-邀请好友 8-账号问题 9-其他问题
    // 标签顺序: [订单问题, 设备问题, 其他]
    // 标签索引对应的type: 0->3(订单问题), 1->4(设备问题), 2->9(其他问题)
    
    NSMutableDictionary *mutDic = [NSMutableDictionary dictionary];
    
    for (BRFAQModel *model in faqList) {
        
        NSString *key = [NSString stringWithFormat:@"%ld",model.type];
        NSMutableArray *mutArr;
        if (mutDic[key]) {
            mutArr = [NSMutableArray  arrayWithArray:mutDic[key]];
        }else {
            mutArr = [NSMutableArray array];
        }
        [mutArr addObject:model];
        
        mutDic[key] = mutArr;
    }
    
    // 按照标签顺序排列：订单问题(3), 设备问题(4), 其他(9)
    NSArray *typeOrder = @[@"3", @"4", @"9"];
    NSMutableArray *orderedKeys = [NSMutableArray array];
    
    for (NSString *typeKey in typeOrder) {
        if (mutDic[typeKey] && [mutDic[typeKey] count] > 0) {
            [orderedKeys addObject:typeKey];
        }
    }
    
    self.datas = orderedKeys;
    return mutDic;
}

#pragma mark - ACTION --
- (void)feedbackClick {
    
    BROderReportViewController *rVC  = [[BROderReportViewController alloc] init];
    rVC.vcType = Report_FAQ;
    rVC.feedbackIn = 0;
    [self.navigationController pushViewController:rVC animated:YES];
}

- (void)supportClick {
    
    [self.supportView show];
}

- (void)setSelIndex:(NSInteger)selIndex {
    _selIndex = selIndex;
    
    
    [self.tableView reloadData];
}

- (void)br_blockAction {
    WS(weakSelf);
    self.navView.rightClickBlock = ^{
        [weakSelf supportClick];
    };
    
    
    self.faqCategoryView.itemSeletedBlock = ^(NSInteger index) {
        weakSelf.selIndex = index;
    };
}

#pragma mark - tableView Delegate --

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    // selIndex 是标签索引，需要转换为对应的 type key
    NSString *typeKey = [self getTypeKeyForTabIndex:self.selIndex];
    NSArray *datas = self.dataDic[typeKey];
    return datas ? datas.count : 0;
}

/// 根据标签索引获取对应的type key
/// @param tabIndex 标签索引: 0->订单问题, 1->设备问题, 2->其他
- (NSString *)getTypeKeyForTabIndex:(NSInteger)tabIndex {
    // 标签顺序: [订单问题, 设备问题, 其他]
    // 对应的type: [3, 4, 9]
    NSArray *typeKeys = @[@"3", @"4", @"9"];
    if (tabIndex >= 0 && tabIndex < typeKeys.count) {
        return typeKeys[tabIndex];
    }
    return @"3";  // 默认返回订单问题
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 34;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (CGFloat)br_getCellHeight:(NSDictionary *)dic {
    CGFloat h = 0;
    for (BRFAQModel *model in dic) {
        if (model.cell_h != 0) {
            h += model.cell_h;
            
        }else {
            NSString *string = model.title;
            model.cell_h = [string jk_heightWithFont:[UIFont br_fontM:14] constrainedToWidth:kScreenWidth - 134.] + 27.;
            h += model.cell_h;
        }
    }
    return h;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BRFAQListCell *cell  = [tableView dequeueReusableCellWithIdentifier:@"BRFAQListCell"];
    NSString *typeKey = [self getTypeKeyForTabIndex:self.selIndex];
    NSArray *datas = self.dataDic[typeKey];
    if (datas && indexPath.row < datas.count) {
    BRFAQModel *model = datas[indexPath.row];
    cell.titleL.text = model.title;
    }
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *typeKey = [self getTypeKeyForTabIndex:self.selIndex];
    NSArray *datas = self.dataDic[typeKey];
    if (datas && indexPath.row < datas.count) {
    BRFAQModel *model = datas[indexPath.row];
    
    BRFAQDetailViewController  *detVC  = [BRFAQDetailViewController new];
    detVC.dto = model;
    [self.navigationController pushViewController:detVC animated:YES];
    }
}

#pragma mark - SET UI --
- (void)setUI {
    
    [self br_createTop:Localized(@"menu_helpCentre") imageRStr:@"help_customer"];
    self.navView.popView.hidden = NO;
    
    self.tableView.estimatedRowHeight = 100;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.backgroundColor = UIColor.clearColor;
//    self.tableView.rowHeight = 144;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BRFAQListCell class]) bundle:nil] forCellReuseIdentifier:@"BRFAQListCell"];
    [self.tableView registerClass:[BRFAQListCell class] forCellReuseIdentifier:@"BRFAQListCell"];

    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, kSafeAreaTopHeight , kScreenWidth, 0)];
    [self.view addSubview:headView];
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(kSafeAreaTopHeight);
        make.left.right.offset(0);
    }];
    
    UIView *topTitleView = [[UIView alloc] init];
    [headView addSubview:topTitleView];
    [topTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(8);
        make.left.right.offset(0);
    }];
    
    QMUILabel *titleL = [BRToolsView br_label:Localized(@"help_hello") textColor:kColorTitle font:[UIFont fontB:28]];
    [topTitleView addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.top.offset(14);
    }];
    QMUILabel *subL = [BRToolsView br_label:Localized(@"help_pbHappyHelp") textColor:kColorTitle66B font:[UIFont fontM:12]];
    [topTitleView addSubview:subL];
    [subL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.top.equalTo(titleL.mas_bottom).offset(4);
        make.bottom.offset(-14);
    }];
    
    QMUIButton *fbBtn = [[QMUIButton alloc] init];
    [fbBtn setTitleColor:kColorMain forState:UIControlStateNormal];
    [fbBtn setTitle:Localized(@"help_feedback") forState:UIControlStateNormal];
    [fbBtn setImage:UIImageMake(@"arrow_right_green22") forState:UIControlStateNormal];
    fbBtn.imagePosition = QMUIButtonImagePositionRight;
    fbBtn.titleLabel.font = [UIFont fontS:14];
    [topTitleView addSubview:fbBtn];
    [fbBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.right.offset(-14);
        make.height.mas_equalTo(44);
    }];
    [fbBtn addTarget:self action:@selector(feedbackClick) forControlEvents:UIControlEventTouchUpInside];
    // 屏蔽意见反馈按钮
    fbBtn.hidden = YES;
    
//    [self.faqCategoryView br_itemAddShadow];
    [headView addSubview:self.faqCategoryView];
    [self.faqCategoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.height.mas_equalTo(44);
        make.top.equalTo(topTitleView.mas_bottom).offset(0);
        make.bottom.offset(-14);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.equalTo(headView.mas_bottom).offset(0);
    }];
    
    
    
    
//    self.tableView.contentView.backgroundColor = UIColor.clearColor;
    self.tableView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.07].CGColor;
    self.tableView.layer.shadowOffset = CGSizeMake(0,6);
    self.tableView.layer.shadowRadius = 16;
    self.tableView.layer.shadowOpacity = 1;
    
//    CGFloat bottom_h = 82 + kSafeAreaBottomHeight;
//    self.tableView.frame = CGRectMake(0, kSafeAreaTopHeight, kScreenWidth, kScreenHeight - kSafeAreaTopHeight - bottom_h);
    
    
//    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - bottom_h, kScreenWidth, bottom_h)];
//    [self.view addSubview:bottomView];
    
//    CGFloat btn_w = (kScreenWidth - 48) / 2.0;
//    QMUIButton *feeback = [[QMUIButton alloc] initWithFrame:CGRectMake(16, 16, btn_w, 50)];
//    feeback.qmui_borderColor = UIColor.qd_rentLBTitleColor;
//    feeback.qmui_borderPosition = QMUIViewBorderPositionTop | QMUIViewBorderPositionBottom | QMUIViewBorderPositionLeft | QMUIViewBorderPositionRight;
//    feeback.qmui_borderWidth = 1;
////    feeback.q
//    feeback.backgroundColor = UIColor.qd_backgroundColor;
//    [feeback setTitleColor:UIColor.qd_rentLBTitleColor forState:UIControlStateNormal];
//    feeback.titleLabel.font = [UIFont br_fontB:16];
//    [feeback setTitle:Localized(@"Help_feeback") forState:UIControlStateNormal];
//    [bottomView addSubview:feeback];
//
//    QMUIButton *supBtn = [[QMUIButton alloc] initWithFrame:CGRectMake(32 + btn_w , 16, btn_w, 50)];
//    [supBtn setTitleColor:UIColorWhite forState:UIControlStateNormal];
//    [supBtn setBackgroundImage:UIImage.qd_homeScanBtnImage forState:UIControlStateNormal];
//    supBtn.layer.masksToBounds = YES;
//    supBtn.titleLabel.font = [UIFont br_fontB:16];
//    [supBtn setTitle:Localized(@"Help_support") forState:UIControlStateNormal];
//    [bottomView addSubview:supBtn];
//
//
//    [feeback addTarget:self action:@selector(feedbackClick) forControlEvents:UIControlEventTouchUpInside];
//    [supBtn addTarget:self action:@selector(supportClick) forControlEvents:UIControlEventTouchUpInside];
//
    [self.view addSubview:self.supportView];
}

- (YGCategoryCustomView *)faqCategoryView {
    if (_faqCategoryView == nil) {
        // 删除"支付问题"标签，只保留：订单问题、设备问题、其他
        _faqCategoryView = [[YGCategoryCustomView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 28, 44) titles:@[Localized(@"help_rentalOrder"),Localized(@"help_device"),Localized(@"help_others")]];
        _faqCategoryView.selColor = UIColor.whiteColor;
        _faqCategoryView.itemBGColor = kColorMain;
    }
    return _faqCategoryView;
}

- (BRSupportView *)supportView {
    
    if (_supportView == nil) {
        _supportView = [[BRSupportView alloc] initWithFrame:self.view.bounds];
    }
    
    return _supportView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
